package com.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.sql.Date;
import java.util.Base64;
import java.util.UUID;

/*
 *  @author 雨安
 *  类名： JwtUtils
 *  创建时间：2024/3/18
 */
public class JwtUtil {
    //有效期为
    public static final Long JWT_TTL = 60 * 60 * 1000L;

    //设置密钥明文
    public static final String JWT_KEY = "yuan";

    //UUID生成
    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-","");
    }

    //生成jwt 支持json格式数据
    public static String createJWT(String subject){
        //拿到jwt
        JwtBuilder builder = getJwtBuilder(subject,null,getUUID());
        //返回jwt构建
        return builder.compact();
    }

    //生成jwt
    public static JwtBuilder getJwtBuilder(String subject,Long ttlMillis,String uuid){
        //使用的加密方法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        //密钥
        SecretKey secretKey = generlKey();
        //当前时间戳
        long nowMillis = System.currentTimeMillis();
        //转换日期
        Date now = new Date(nowMillis);
        //判断是否为null
        if (ttlMillis == null){
            //赋值
            ttlMillis = JwtUtil.JWT_TTL;
        }
        //时间
        long expMillis = nowMillis + ttlMillis;
        //转换
        Date expDate = new Date(expMillis);
        //返回构造
        return Jwts.builder()
                .setId(uuid) //唯一id
                .setSubject(subject) //主题 可以是JSON数据
                .setIssuer("YeYuAn") //签发者
                .setIssuedAt(now) //签发时间
                .signWith(signatureAlgorithm,secretKey) //使用HS256对称加密算法签名,第二个参数为密钥
                .setExpiration(expDate); //结束时间
    }

    //创建token
    public static String createJWT(String id,String subject,Long ttlMillis){
        JwtBuilder builder = getJwtBuilder(subject,ttlMillis,id);//设置过期时间
        return builder.compact();
    }

    public static void main(String[] args) {
        //加密jwt
        String jwt = createJWT("YeYuAn");
        //解密jwt
        Claims claims = parseJWT(jwt);

        System.out.println(jwt);

        System.out.println(claims.getSubject());
    }

    //生成加密后的密钥 secretKey
    public static SecretKey generlKey(){
        //Base64加密
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        //设置密钥
        SecretKey key = new SecretKeySpec(encodedKey,0,encodedKey.length,"AES");
        //返回
        return key;
    }

    //解析JWT
    public static Claims parseJWT(String jwt){
        //拿到key
        SecretKey secretKey = generlKey();
        //返回
        return Jwts.parser()
                .setSigningKey(secretKey) //设置密钥
                .parseClaimsJws(jwt)
                .getBody();
    }










}
